package com.czk.codec;

import com.czk.utils.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 对象编码器
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/22 11:03
 */
public class ObjEncoder extends MessageToByteEncoder {
    private Class<?> genericClass;

    public ObjEncoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        // 是否是同一类型
        if (genericClass.isInstance(o)) {
            // 转为字节数组
            byte[] bytes = SerializationUtil.serializer(o);
            // 写入
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
